/*
 * @Author: Zeratul
 * @Date: 2020-08-19 19:52:05
 * @LastEditTime: 2020-08-28 11:46:36
 * @FilePath: \sz-h5-2003-react-mobile\zhangminhui\eleme-react\eleme-apiServer\app.js
 */
var createError = require("http-errors");
var express = require("express");
const cors = require("cors");
const md5 = require("md5");
const moment = require("moment");
const token = require("jsonwebtoken");
const session = require("express-session");
("express-session");
const { connection, spell, SetID, getCode } = require("./config");
const mysql = require("mysql");
const bodyParser = require("body-parser");
const multer = require("multer");
const {
  userModel,
  productModel,
  addressModel,
  tagItemModel,
  shopcarModel,
  levelModel,
  vipModel,
  shopkeeperModel,
  mealModel,
  orderModel,
} = require("./model/dataModels");
const Core = require("@alicloud/pop-core");

var app = express();

var client = new Core({
  accessKeyId: "LTAI4GBMho6m1ZMJmENtHgDw",
  accessKeySecret: "6SY9NUDJpcYiqMsj3WGp9ivOeLHuXl",
  endpoint: "https://dysmsapi.aliyuncs.com",
  apiVersion: "2017-05-25",
});
var requestOption = {
  method: "POST",
};

var upload = multer({ dest: "../www/upload" });
//设置跨域
app.use(cors());
//设置body-parser
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);
//建立数据库连接
var myCon = mysql.createConnection(connection);
myCon.connect();
//设置session
app.use(
  session({
    secret: "Avada Kedavra",
    resave: false,
    saveUninitialized: true,
    cookie: {
      maxAge: 1000 * 60 * 60,
    },
  })
);

//#region 用户
/**
 * 用户-注册
 *@param {String} userName
 *@param {String} password
 *@param {String} telephone
 */
app.post("/api/user/regist", function (req, res) {
  let body = req.body;
  let tablename = "users";
  let userID = SetID(tablename);
  userModel["userID"] = userID;
  for (let key in body) {
    if (key == "password") {
      body["password"] = md5(spell + body["password"] + spell);
    }
    if (body[key]) {
      userModel[key] = body[key];
    }
  }
  let sqlQuery = "select * from users where telephone=" + userModel.telephone;
  console.log(sqlQuery);
  myCon.query(sqlQuery, function (queryerror, queryresults, queryfields) {
    if (!queryerror) {
      if (queryresults.length > 0) {
        res.send({ code: 204, content: "用户名已存在" });
      } else {
        console.log("用户不存在");
        let arrKeys = [];
        let arrValues = [];
        for (let key in userModel) {
          if (userModel[key]) {
            arrKeys.push(key);
            arrValues.push("'" + userModel[key] + "'");
          }
        }
        let sql =
          "insert into users(" +
          arrKeys.toString() +
          ") values (" +
          arrValues.toString() +
          ")";
        console.log(sql);
        myCon.query(sql, function (error, results, fields) {
          if (!error) {
            res.send({ code: 200, content: "success", results });
          } else {
            res.send({ code: 500, content: "error:", error });
          }
        });
      }
    }
  });
});

/**
 * 用户-登陆
 * @param {String} telephone
 * @param {string} password
 */
app.post("/api/user/login", function (req, res) {
  let body = req.body;
  console.log(body);
  for (let key in body) {
    if (body[key]) {
      userModel[key] = body[key];
    }
  }
  userModel["password"] = md5(spell + userModel["password"] + spell);
  let sql =
    "select * from users where telephone='" +
    userModel.telephone +
    "' and password='" +
    userModel.password +
    "'";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      if (results.length > 0) {
        res.send({ code: 200, content: "success", results });
      } else {
        res.send({ code: 404, content: "用户名或密码错误" });
      }
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户-验证码登陆
 * @param {String} telephone
 */
app.post("/api/user/loginByCode", function (req, res) {
  let body = req.body;
  let sqlQuery = "select * from users where telephone=" + body.telephone;
  console.log(sqlQuery);
  myCon.query(sqlQuery, function (sqlQueryError, sqlQueryResults) {
    if (!sqlQueryError) {
      if (sqlQueryResults.length > 0) {
        res.send({ code: 200, content: "success", sqlQueryResults });
      } else {
        res.send({ code: 404, content: "用户不存在,跳转到注册" });
      }
    } else {
      res.send({ code: 500, content: "error:", sqlQueryError });
      return;
    }
  });
});
/**
 * 用户-修改用户信息
 * @param {String} userID
 * @param {Object} userModel
 */
app.post("/api/user/modifyUserInfo", function (req, res) {
  let body = req.body;
  for (let key in body) {
    userModel[key] = body[key];
  }
  let arrUpdate = [];
  for (let key in userModel) {
    if (userModel[key]) {
      arrUpdate.push(key + "='" + userModel[key] + "'");
    }
  }
  let sql =
    "update users set " +
    arrUpdate.toString() +
    "where userID=" +
    userModel.userID;
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 主页-搜索
 * @param {String} inputValue
 */
app.post("/api/index/searhInfo", function (req, res) {
  let body = req.body;
  let sql =
    "SELECT productName as result FROM products where productName like '%" +
    body.inputValue +
    "%' union select sortOName as result from sort_one where sortOName like '%" +
    body.inputValue +
    "%' union select sortTName as result from sort_two where sortTName like '%" +
    body.inputValue +
    "%' union select shopTypeOName as result from shop_type_one where shopTypeOName like '%" +
    body.inputValue +
    "%' union select shopTypeTName as result from shop_type_two where shopTypeTName like '%" +
    body.inputValue +
    "%'";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 主页-获取一级分类导航
 */
app.get("/api/index/getSortOneList", function (req, res) {
  let sql = "select * from sort_one";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 主页-获取二级分类导航
 * @param {String} sortOID
 */
app.post("/api/index/getSortTwoList", function (req, res) {
  let body = req.body;
  let sql = "select * from sort_two where sortOID=" + body.sortOID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 主页-根据一、二级分类，获取商品列表
 * @param {String} sortOID
 * @param {String} sortTID
 */
app.post("/api/index/getProductsBySortOID&SortTID", function (req, res) {
  let body = req.body;
  let sql =
    "select products.*,sort_one.*,sort_two.sortTID,sort_two.sortTName from products,sort_one,sort_two where products.sortOID=sort_one.sortOID and products.sortTID=sort_two.sortTID and products.sortOID=" +
    body.sortOID +
    " and products.sortTID=" +
    body.sortTID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 用户页-修改地址
 * @param {String} userID
 * @param {String} tagID
 * @param {Object} addressObj //province city district detail addr_LNG addr_LAT必填
 */
app.post("/api/user/addToAddress", function (req, res) {
  let body = req.body;

  let tablename = "addresses";
  let addressID = SetID(tablename);
  addressModel.addressID = addressID;
  for (let key in body) {
    addressModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in addressModel) {
    if (addressModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + addressModel[key] + "'");
    }
  }
  console.log(addressModel);
  let sql =
    "insert into addresses(" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
//#endregion
/**
 * 手机获取短信验证码
 * @param {String} telephone
 * @param {String} way regist/login
 */
app.post("/api/user/getSMSCode", function (req, res) {
  let body = req.body;
  console.log(body);
  let code = getCode();

  var params = {
    RegionId: "cn-hangzhou",
    PhoneNumbers: body.telephone,
    SignName: "iHome商城",
    TemplateCode: body.way === "login" ? "SMS_200193855" : "SMS_200183714",
    TemplateParam: '{"code":"' + code + '"}',
  };
  console.log(params);
  client.request("SendSms", params, requestOption).then(
    (result) => {
      result.code = code;
      console.log(result);
      res.send(result);
    },
    (ex) => {
      res.send(ex);
      return;
    }
  );
});
/**
 * 控制类-添加标签
 * @param {String} tagName
 */
app.post("/api/control/addTag", function (req, res) {
  let body = req.body;
  let tagID = SetID("tag_items");
  tagItemModel.tagID = tagID;
  for (let key in body) {
    tagItemModel[key] = body[key];
  }
  let arrkeys = [];
  let arrValues = [];
  for (let key in tagItemModel) {
    arrkeys.push(key);
    arrValues.push("'" + tagItemModel[key] + "'");
  }
  console.log(tagItemModel);
  let sql =
    "insert into tag_items (" +
    arrkeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 获取标签
 */
app.get("/api/control/getTags", function (req, res) {
  let sql = "select * from tag_Items";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户类-添加地址
 * @param {userID} tagID
 * @param {string} userID
 * @param {Object} addressModel province/city/district/detail/addrLNG/addr_LAT/isUsual
 */
app.post("/api/user/addNewAddress", function (req, res) {
  let body = req.body;
  let addressID = SetID("addresses");
  addressModel.addressID = addressID;
  for (let key in body) {
    addressModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in addressModel) {
    if (addressModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + addressModel[key] + "'");
    }
  }
  let sql =
    "insert into addresses (" +
    arrKeys.toString() +
    ") values (" +
    arrValues +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 用户-修改地址
 * @param {String} addressID
 * @param {Object} addressModel
 */
app.post("/api/user/modifyAddress", function (req, res) {
  let body = req.body;
  for (let key in body) {
    addressModel[key] = body[key];
  }
  let arrKeys = [];
  for (let key in addressModel) {
    if (addressModel[key]) {
      arrKeys.push(key + "='" + addressModel[key] + "'");
    }
  }
  let sql =
    "update addresses set " +
    arrKeys.toString() +
    " where addressID=" +
    addressModel.addressID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 用户-单商品添加购物车
 * @param {String} userID
 * @param {String} productID
 * @param {String} productnum
 */
app.post("/api/user/addToCart", function (req, res) {
  let body = req.body;
  let cartID = SetID("shopcars");
  shopcarModel.cartID = cartID;
  for (let key in body) {
    shopcarModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in shopcarModel) {
    if (shopcarModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + shopcarModel[key] + "'");
    }
  }
  let sql =
    "insert into shopcars (" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      results["cartID"]=cartID;
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户-修改购物车数量
 * @param {String} cartID
 * @param {String} productnum
 */
app.post("/api/user/modifyCart", function (req, res) {
  let body = req.body;
  let sql =
    "update shopcars set productnum=" +
    body.productnum +
    " where cartID=" +
    body.cartID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {

      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户-删除购物车
 * @param {String} cartID
 */
app.post("/api/user/deleteCart", function (req, res) {
  let body = req.body;
  let sql = "delete from shopcars where cartID=" + body.cartID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 用户-获取当前用户所有购物车商品信息
 * @param {String} userID
 */
app.post("/api/user/getAllCartByUserID", function (req, res) {
  let body = req.body;
  let sql =
    "select shopcars.cartID,shopcars.userID,shopcars.productnum,products.*,shopkeeper.* from shopcars,products,shopkeeper where shopcars.productID=products.productID and shopkeeper.shopID=products.shopID and shopcars.userID=" +
    body.userID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 控制-添加vip等级经验信息
 * @param {String} level
 * @param {String} totalExps
 */
app.post("/api/control/addVip", function (req, res) {
  let body = req.body;
  let levelID = SetID("level");
  levelModel.levelID = levelID;
  for (let key in body) {
    levelModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in levelModel) {
    if (levelModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + levelModel[key] + "'");
    }
  }
  let sql =
    "insert into level(" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 会员-加入会员
 * @param {String} userID
 */
app.post("/api/vip/addToVip", function (req, res) {
  let body = req.body;
  let vipID = SetID("vip_members");
  vipModel.vipID = vipID;
  let sql =
    "insert into vip_members (vipID,userID) values(" +
    vipModel.vipID +
    "," +
    body.userID +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 店铺-添加店铺
 * @param {String} userID
 * @param {Object} shopkeeperModel
 */
app.post("/api/shop/addShopkeeper", function (req, res) {
  let body = req.body;
  let shopID = SetID("shopkeepers");
  shopkeeperModel.shopID = shopID;
  for (let key in body) {
    shopkeeperModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in shopkeeperModel) {
    if (shopkeeperModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + shopkeeperModel[key] + "'");
    }
  }
  let sql =
    "insert into shopkeeper (" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
    }
  });
});
/**
 * 获取店铺信息
 */
app.get("/api/user/getAllShops", function (req, res) {
  let sql = "select * from shopkeeper order by monthlySales desc";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 根据商家ID获取商家自定义分类
 * @param {String} shopID
 */
app.post("/api/user/getCustomizedSortByShopID", function (req, res) {
  let body = req.body;
  let sql =
    "select * from sort_one where isCustomized =1 and shopID=" + body.shopID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 用户-收藏商家
 * @param {String} userID
 * @param {String} shopID
 */
app.post("/apiuser/addToFollows", function (req, res) {
  let body = req.body;
  let followID = SetID("follows");
  let sql =
    "insert into follows (followID,userID,shopID) values (" +
    followID +
    "," +
    body.userID +
    "," +
    body.shopID +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户-取消收藏
 * @param {String} followID
 */
app.post("/api/user/cancelFollow", function (req, res) {
  let body = req.body;
  let sql = "delete from follows where followID=" + body.followID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 用户查看收藏商家
 * @param {String} userID
 */
app.post("/api/user/findAllFollows", function (req, res) {
  let body = req.body;
  let sql =
    "select shopkeeper.*,follows.followID  from follows,shopkeeper where shopkeeper.shopID=follows.shopID where follows.userID=" +
    body.userID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 添加新商品
 * @param {String} shopID
 */
app.post("/api/shop/addProduct", function (req, res) {
  let body = req.body;
  let productID = SetID("products");
  productModel.productID = productID;
  for (let key in body) {
    productModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in productModel) {
    if (productModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + productModel[key] + "'");
    }
  }
  var sql =
    "insert into products (" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 商家-添加套餐
 * @param {String} shopID
 *@param {object} mealModel
 */
app.post("/api/shop/addMeal", function (req, res) {
  let body = req.body;
  let mealID = "meals";
  mealModel.mealID = mealID;
  for (let key in body) {
    mealModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in mealModel) {
    if (mealModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + mealModel[key] + "'");
    }
  }
  let sql =
    "insert into meals(" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 商家-添加套餐商品
 * @param {String} mealID
 * @param {String} productID
 */
app.post("/api/shop/addMealProduct", function (req, res) {
  let body = req.body;
  let mdetailID = SetID("meal_details");
  let sql =
    "insert into meal_details(mdetailID,mealID,productID) values (" +
    mdetailID +
    "," +
    body.mealID +
    "," +
    body.productID +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 查看套餐商品
 * @param {string} shopID
 * @param {String} mealID
 */
app.post("/api/findMealDetailByShopID&MealID", function (req, res) {
  let body = req.body;
  let sql =
    "select distinct shopkeeper.*,meals.mealID,meals.discount as mealDiscount,meals.mealName,meals.price as mealPrice,meals.picture as mealPicture,meal_details.mdetailID,products.productID,products.productName,products.inventory,products.MonthlySales as productMonthlySales,products.material,products.discount,products.preferentialRestrictions,products.isSpecially,products.isOff,products.isMeal,products.isSingleSale,products.recommendedNumber,products.picture from shopkeeper,meals,meal_details,products where meals.shopID=shopkeeper.shopID and meal_details.mealID=meals.mealID and meal_details.productID=products.productID and meals.shopID=" +
    body.shopID +
    " and meal_details.mealID= " +
    body.mealID;
});
/**
 * 根据商家ID查看商品信息
 * @param {String} shopID
 */
app.post("/api/user/getProductByShopID", function (req, res) {
  let body = req.body;
  let sql = "select * from products where shopID=" + body.shopID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 根据一级菜单筛选商品
 * @param {String} shopID
 * @param {String} sortOID
 */
app.post("/api/user/getProductBySortTID", function (req, res) {
  let body = req.body;
  let sql =
    "select products.*,sort_one.sortOName,sort_one.isCustomized from products,sort_one where sort_one.isCustomized=1 and sort_one.sortOID=products.sortOID and sort_one.shopID=" +
    body.shopID +
    " and sort_one.sortOID=" +
    body.sortOID +
    "";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
app.post("/api/user/uploadsCommits", upload.array("avatar", 4), function (
  req,
  res
) {
  let body = req.body;
  let file = req.file;
  console.log(body, files);
});
/**
 * 获取当前用户所有地址
 * @param {String} userID
 */
app.post("/api/user/getAllAddressesByUserID", function (req, res) {
  let body = req.body;
  let sql =
    "select addresses.*,tag_items.tagName from addresses,tag_items where addresses.userID=" +
    body.userID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
/**
 * 生成订单
 * @param {String} shopID
 * @param {String} addressID
 * @param {String} cartID
 * @param {String} userID
 * @param {Object} orderModel status/deliveryTime/deliveryWay/payMode/isRecommend/remarks
 */
app.post("/api/user/generateOrder", function (req, res) {
  let body = req.body;
  let orderID = SetID("orders");
  orderModel.orderID = orderID;
  let createTime = moment(Date.now()).format("YYYY-MM-DD HH:mm:ss");
  orderModel.createTime = createTime;
  for (let key in body) {
    orderModel[key] = body[key];
  }
  let arrKeys = [];
  let arrValues = [];
  for (let key in orderModel) {
    if (orderModel[key]) {
      arrKeys.push(key);
      arrValues.push("'" + orderModel[key] + "'");
    }
  }
  console.log(arrKeys);
  let sql =
    "insert into orders (" +
    arrKeys.toString() +
    ") values (" +
    arrValues.toString() +
    ")";
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 查看单订单详情
 * @param {String} orderID
 */
app.post("/api/getOrderList", function (req, res) {
  let body = req.body;
  let sql =
    "select orders.status,orders.createTime,orders.deliveryTime as orderDeleveryTime,orders.deliveryWay,orders.payMode,orders.isRecommend,orders.remarks,shopkeeper.*,addresses.addressID,addresses.detail as addressDetail,tag_items.tagName,shopcars.productnum,users.*,products.productID,products.sortOID,products.productName,products.price as productPrice,products.inventory,products.MonthlySales as productMonthluSales,products.content,products.material,products.discount,products.preferentialRestrictions,products.isSpecially,products.isOff,products.isMeal,products.isSingleSale,products.recommendedNumber,products.picturefrom orders,shopkeeper,addresses,tag_items,shopcars,users,products,sort_one where orders.shopID=shopkeeper.shopID and orders.addressID=addresses.addressID and addresses.tagID=tag_items.tagID and orders.cartID=shopcars.cartID and shopcars.userID=users.userID and shopcars.productID=products.productID and products.sortOID=sort_one.sortOID and orders.orderID=" +
    body.orderID;
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});

/**
 * 查看当前用户所有订单
 * @param {String} userID
 * @param {String} shopID
 */
app.post("/api/getAllOrders", function (req, res) {
  let body = req.body;
  let sql = "select shopcars.*,shopkeeper.*,orders.statuses,orders.createTime,orders.orderDeliveryTime,orders.deliveryWay,orders.payMode,orders.isRecommend,orders.remarks from orders,shopcars,shopkeeper where orders.userID="+body.userID
  console.log(sql);
  myCon.query(sql, function (error, results, fields) {
    if (!error) {
      res.send({ code: 200, content: "success", results });
    } else {
      res.send({ code: 500, content: "error:", error });
      return;
    }
  });
});
module.exports = app;
